from django.contrib.contenttypes.fields import GenericForeignKey
from django.contrib.contenttypes.models import ContentType
from django.db import models
from django.conf import settings

face_files = 'member/face/'


class Member(models.Model):
    FEMAL = 1
    MALE = 2
    GENDER_CHOICES = (
        (FEMAL, '女'),
        (MALE, '男')
    )
    COMMON = 1
    WORKER = 2
    IDENTITY_CHOICE = (
        (COMMON, '普通用户'),
        (WORKER, '工人')
    )
    IDENTITY_JSON = [{'code': item[0], 'codeName': item[1]} for item in IDENTITY_CHOICE]
    user = models.OneToOneField(settings.AUTH_USER_MODEL, editable=False, related_name='member',
                                on_delete=models.PROTECT, verbose_name='会员')
    face_url = models.CharField(verbose_name='头像', max_length=200, null=True)
    province = models.CharField(verbose_name='省份', max_length=50, null=True)
    city = models.CharField(verbose_name='城市', max_length=50, null=True)
    gender = models.PositiveSmallIntegerField(choices=GENDER_CHOICES, verbose_name='性别', null=True)
    identity = models.PositiveSmallIntegerField(choices=IDENTITY_CHOICE, verbose_name='身份', default=COMMON)
    inviter = models.ForeignKey('Member', verbose_name='邀请者', related_name='member_inviter', on_delete=models.PROTECT,
                                null=True, blank=True)

    class Meta:
        db_table = 'member'
        default_permissions = ()
        verbose_name = '会员'


class MemberHouse(models.Model):
    ADORN_BEFORE = 0
    ADORN_ING = 1
    ADORN_AFTER = 2
    ADORN_STATUS_CHOICES = (
        (ADORN_BEFORE, '装修前'),
        (ADORN_ING, '装修中'),
        (ADORN_AFTER, '装修后')
    )
    member = models.ForeignKey(Member, verbose_name='会员', on_delete=models.PROTECT, null=True)
    adorn_status = models.PositiveSmallIntegerField(choices=ADORN_STATUS_CHOICES, verbose_name='装修阶段',
                                                    default=ADORN_BEFORE)
    address = models.CharField(verbose_name='房屋地址', max_length=150)
    people_num = models.IntegerField(verbose_name='常驻人数', null=True)
    house_size = models.FloatField(verbose_name='房屋面积')
    door_model = models.CharField(verbose_name='户型', max_length=20)
    adorn_budget = models.CharField(verbose_name='装修预算', max_length=20, null=True, blank=True)
    mobile = models.CharField(verbose_name='联系方式', max_length=11, null=True, blank=True)

    class Meta:
        db_table = 'member_house'
        verbose_name = '我的房子'


class MemberRecord(models.Model):
    DEFAULT = 0
    INSERT = 1
    DELETE = 2
    COMMENT = 3
    LIKE = 4
    COLLECT = 5
    SIGN = 6
    SET_PASSWORD = 7
    BROWSE = 8

    OPERATE_CHOICE = (
        (INSERT, '添加'),
        (DELETE, '删除'),
        (COMMENT, '评论'),
        (LIKE, '点赞'),
        (COLLECT, '收藏'),
        (SIGN, '注册'),
        (SET_PASSWORD, '修改密码'),
        (BROWSE, '浏览'),
    )
    content_type = models.ForeignKey(ContentType, on_delete=models.PROTECT)
    object_id = models.PositiveIntegerField()
    content_object = GenericForeignKey(
        ct_field="content_type",
        fk_field="object_id"
    )
    member = models.ForeignKey(Member, verbose_name='会员', on_delete=models.PROTECT)
    operate = models.PositiveIntegerField(verbose_name='用户操作', choices=OPERATE_CHOICE, default=DEFAULT)
    describe = models.CharField(verbose_name='记录描述', max_length=200, null=True)
    extra = models.CharField(verbose_name='数据', max_length=500, null=True)
    create_time = models.DateTimeField(verbose_name='创建时间', auto_now_add=True, editable=False)

    class Meta:
        db_table = 'member_record'
        ordering = ('-create_time',)
        verbose_name = '操作纪录表'

    @staticmethod
    def check_user_operate(user, content_type, object_id, operate):
        '''判断用户的操作'''
        member_record = MemberRecord.objects.filter(content_type=content_type, object_id=object_id,
                                                    user=user, operate=operate).first()
        if member_record:
            return True
        return False

    @staticmethod
    def get_content_type(model_name):
        return ContentType.objects.get(model=model_name.lower())

    @staticmethod
    def is_like(instance, member):
        member_record = MemberRecord.objects.filter(
            content_type=MemberRecord.get_content_type(instance.__class__.__name__),
            object_id=instance.id,
            member=member,
            operate=MemberRecord.LIKE).first()

        if member_record:
            return True
        return False

    @staticmethod
    def like_operate(instance, member):
        member_record = MemberRecord.objects.filter(
            content_type=MemberRecord.get_content_type(instance.__class__.__name__),
            object_id=instance.id,
            member=member,
            operate=MemberRecord.LIKE).first()
        if member_record:
            # 存在，删除
            instance.like_count -= 1
            instance.save()
            member_record.delete()
            return False, '取消点赞'

        # 不存在，创建
        instance.like_count += 1
        instance.save()
        MemberRecord.objects.create(content_object=instance, member=member,
                                    operate=MemberRecord.LIKE,
                                    describe='点赞')
        return True, '成功点赞'

    @staticmethod
    def is_collect(instance, member):
        member_record = MemberRecord.objects.filter(
            content_type=MemberRecord.get_content_type(instance.__class__.__name__),
            object_id=instance.id,
            member=member,
            operate=MemberRecord.COLLECT).first()
        if member_record:
            return True
        return False

    @staticmethod
    def collect_operate(instance, member):
        member_record = MemberRecord.objects.filter(
            content_type=MemberRecord.get_content_type(instance.__class__.__name__),
            object_id=instance.id,
            member=member,
            operate=MemberRecord.COLLECT).first()
        if member_record:
            # 存在，删除
            instance.collect_count -= 1
            instance.save()
            member_record.delete()
            return False, '取消收藏'

        # 不存在，创建
        instance.collect_count += 1
        instance.save()
        MemberRecord.objects.create(content_object=instance, member=member,
                                    operate=MemberRecord.COLLECT, describe='收藏')
        return True, '成功收藏'
